package com.supeng.PMdepot.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.supeng.PMdepot.MApplication;
import com.supeng.PMdepot.util.FileUtils;
import com.supeng.PMdepot.util.UnzipFromAssets;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库相关操作类
 */
public class DataBaseHelper {
    /*  DataBaseHelper.getInstance().insert(false,"1","12");
          DataBaseHelper.getInstance().insert(false,"1","13");
          List<String> list=DataBaseHelper.getInstance().getAllRedServerid(false,"1");
          int redCount=DataBaseHelper.getInstance().getRedCount(false,"1");
          Toast.makeText(getActivity(),"redCount="+redCount,0).show();*/
    // 数据库名称
    private static String DB_NAME = "weixu.db";
    private static String DB_ZIP_NAME = "weixu.zip";

    public SQLiteDatabase db;
    private static DataBaseHelper dataHelper = null;

    /**
     * 第一次实例化时调用
     *
     * @return
     */
    public synchronized static DataBaseHelper getInstance() {
        if (dataHelper == null) {
            dataHelper = new DataBaseHelper(MApplication.getContext());
        }
        return dataHelper;
    }

    /**
     * @param context context
     * @brief 构造函数
     */
    public DataBaseHelper(Context context) {
        db = openDatabase(context);
    }

    /**
     * 加载外部DB文件
     *
     * @param context
     * @return
     */
    public SQLiteDatabase openDatabase(Context context) {
        try {
            // 解压缩zip到应用内部data文件夹，然后加载数据库db
            String databaseFilename = FileUtils.getSeparatorChar(context.getFilesDir().getAbsolutePath()) + DB_NAME;
            if (!(new File(databaseFilename)).exists()) {
                UnzipFromAssets.unZip(context, DB_ZIP_NAME, context.getFilesDir().getAbsolutePath(), true);
            }
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
                    databaseFilename, null);
            return database;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭数据库
     *
     * @return 无
     */
    public void close() {
        db.close();
    }

    /**
     * 插入红点
     */
    public void insert(boolean isWeiChuli,String userid, String serverid) {
        try {
            if(isWeiChuli) {
                db.execSQL(
                        "INSERT INTO "
                                + SqliteHelper.WEICHULI
                                + "(" + SqliteHelper.userid
                                + "," + SqliteHelper.serverid
                                + ")"
                                + " VALUES (?,?)",
                        new Object[]{userid, serverid});
            }else{
                db.execSQL(
                        "INSERT INTO "
                                + SqliteHelper.CHULIZHONG
                                + "(" + SqliteHelper.userid
                                + "," + SqliteHelper.serverid
                                + ")"
                                + " VALUES (?,?)",
                        new Object[]{userid, serverid});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取已清除红点
     * @return
     */
    public List<String> getAllRedServerid(boolean isWeiChuli,String userid) {
        String sql="";
        if(isWeiChuli){
            sql = String.format("SELECT * FROM %s", SqliteHelper.WEICHULI + " WHERE " + SqliteHelper.userid + "='" + userid+"'");
        }else{
            sql = String.format("SELECT * FROM %s", SqliteHelper.CHULIZHONG + " WHERE " + SqliteHelper.userid + "='" + userid+"'");
        }
        Cursor cursor = db.rawQuery(sql, null);
        cursor.moveToFirst();

        List<String> redList = new ArrayList<>();
        while (!cursor.isAfterLast()) {
            String service_id = cursor.getString(cursor.getColumnIndex(SqliteHelper.serverid));
            redList.add(service_id);
            cursor.moveToNext();
        }
        cursor.close();
        return redList;
    }

  public int getRedCount(boolean isWeiChuli,String userid){
        int redCount=0;
      String sql="";
        if(isWeiChuli) {
            sql = "select count(*) from " + SqliteHelper.WEICHULI + " WHERE " + SqliteHelper.userid + "='" + userid + "'";
        }else{
            sql = "select count(*) from " + SqliteHelper.CHULIZHONG + " WHERE " + SqliteHelper.userid + "='" + userid + "'";

        }
      Cursor cursor = db.rawQuery(sql, null);
      cursor.moveToFirst();
      while (!cursor.isAfterLast()){
          redCount=cursor.getInt(0);
          cursor.moveToNext();
      }
      cursor.close();
      return redCount;
  }
}
